package com.powernode.lambda.lambda;


import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 *  闭包的实际应用
 */
public class Lambda09 {
    public static void main(String[] args) {
        ArrayList<Runnable> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
//            报错Variable used in lambda expression should be final or effectively final
//            因为闭包的限制，i的值不能变化
//            Runnable task = () ->{
//                System.out.println("执行任务" + (i+1));
//            };
            //把i+1赋值给k，这样k每次都是不变化的新的值
            int k = i + 1;
            Runnable task = () ->{
                System.out.println("执行任务" + k);
            };

            list.add(task);
        }
        ExecutorService executorService = Executors.newFixedThreadPool(list.size());
        for (Runnable runnable : list) {
            executorService.submit(runnable);
        }
    }


}
